package it.ap.sa.acqua.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import it.ap.sa.acqua.auth.service.CustomAuthenticationProvider;
 
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
	@Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;
	
    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;
 
    @Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.authenticationProvider(customAuthenticationProvider);
	}
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        	.csrf().disable()
        	.authorizeRequests()
	        	/** resources:  accesso non protetto **/
        		.antMatchers("/banana").permitAll()
        		.antMatchers("/img/**").permitAll()
        		.antMatchers("/images/**").permitAll()
				.antMatchers("/css/**").permitAll()
				.antMatchers("/js/**").permitAll()
				.antMatchers("/bundle/**").permitAll()
				.antMatchers("/plugin/**").permitAll()
				.antMatchers("/shared/**").permitAll()
				.antMatchers("/pages/**").permitAll()
				.antMatchers("/index").permitAll()
				/** accesso protetto **/
				.antMatchers("/fishCtrl/**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
				.antMatchers("/plantCtrl/**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
				.antMatchers("/tankCtrl/**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
        		
            .and()
            	.formLogin()
            		.loginPage("/login").permitAll()
            		.loginProcessingUrl("/login")
            			.usernameParameter("ssoId")
            			.passwordParameter("password")
    				.failureUrl("/login?error").permitAll()
    				.defaultSuccessUrl("/tankCtrl/myTank", true)
    		.and()
    			.logout()
    				.deleteCookies("JSESSIONID")
    				.invalidateHttpSession(true)
    				.logoutUrl("/logout")
    				.logoutRequestMatcher(new AntPathRequestMatcher("/logout", null, true))
    				.logoutSuccessUrl("/login?logout").permitAll()
    		.and()
    			.sessionManagement()
    				.enableSessionUrlRewriting(true)
    				.sessionAuthenticationErrorUrl("/login?error")
    				.maximumSessions(20)
    				.maxSessionsPreventsLogin(true)
    				.expiredUrl("/concurrentSessionExpired");
    }
 
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
 
    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }
 
}